package com.dearbinge.data.service.impl.thumbs;

import com.dearbinge.data.api.thumbs.ThumbsService;
import com.dearbinge.data.api.userWallet.UserWalletService;
import com.dearbinge.data.dao.*;
import com.dearbinge.data.pojo.moneyDetail.MoneyDetail;
import com.dearbinge.data.pojo.orderDetailTable.OrderDetailTable;
import com.dearbinge.data.pojo.showField.ShowField;
import com.dearbinge.data.pojo.thumbs.Thumbs;
import com.dearbinge.data.pojo.thumbs.vo.ThumbsResult;
import com.dearbinge.data.pojo.transactionFlow.TransactionFlow;
import com.dearbinge.data.pojo.user.User;
import com.dearbinge.data.pojo.userWallet.UserWallet;
import com.dearbinge.utils.money.HongBaoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Transactional
@Service(value = "thumbsService")
public class ThumbsServiceImpl implements ThumbsService {

    @Autowired
    private ThumbsMapper thumbsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShowFieldMapper showFieldMapper;

    @Autowired
    private OrderDetailTableMapper orderDetailTableMapper;

    @Autowired
    private MoneyDetailMapper moneyDetailMapper;

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private TransactionFlowMapper transactionFlowMapper;


    @Override
    public Integer update(Thumbs thumbs) {
        Integer dataCode = thumbsMapper.update(thumbs);
        return dataCode;
    }

    @Override
    public String insert(Thumbs thumbs) {
        Integer dataCode = null;
        try {
            ShowField sf = new ShowField();
            ShowField showField = showFieldMapper.getById(Integer.valueOf(thumbs.getIsThumbsId()));
            Integer thumbsCount = 1;
            dataCode = thumbsMapper.insert(thumbs);
            String code = "501";
            if (dataCode > 0) {
                if (showField != null) {
                    thumbsCount = Integer.valueOf(showField.getThumbsCount());
                    thumbsCount++;
                    if (showField.getThumbsType() == 1 && thumbs.getThumbsType() == 3) {
                            OrderDetailTable orderDetailTable = orderDetailTableMapper.getById(showField.getOrderId());
                            if (orderDetailTable.getRedNumber() > 0){
                                Integer redNumber = orderDetailTable.getRedNumber();
                                BigDecimal redMoney = orderDetailTable.getRedMoney();
                                synchronized(this){
                                    List<BigDecimal> moneys = HongBaoUtil.math(redMoney, redNumber);
                                    MoneyDetail moneyDetail = new MoneyDetail();
                                    moneyDetail.setMoney(moneys.get(0));
                                    moneyDetail.setCommodityId(orderDetailTable.getCommodityId());
                                    moneyDetail.setUserId(thumbs.getUserId());
                                    moneyDetail.setOrderId(orderDetailTable.getId().toString());
                                    moneyDetail.setSource(1);
                                    moneyDetail.setStatus(1);
                                    orderDetailTable.setRedMoney(orderDetailTable.getRedMoney().subtract(moneys.get(0)));
                                    orderDetailTable.setRedNumber(orderDetailTable.getRedNumber()-1);
                                    orderDetailTable.setModifyBy(thumbs.getUserId());
                                    orderDetailTable.setIsRelease("1");
                                    TransactionFlow transactionFlow = new TransactionFlow();
                                    transactionFlow.setUserId(thumbs.getUserId());
                                    transactionFlow.setTfType(1);
                                    transactionFlow.setMoney(moneys.get(0));
                                    transactionFlow.setSource(1);
                                    transactionFlow.setFtStatus(1);
                                    transactionFlowMapper.insert(transactionFlow);
                                    orderDetailTableMapper.update(orderDetailTable);
                                    userWalletMapper.updateMoneyByUserId(thumbs.getUserId(),moneys.get(0));
                                    if (moneyDetailMapper.insert(moneyDetail) > 0) {
                                        sf.setId(showField.getId());
                                        sf.setThumbsCount(thumbsCount);
                                        showFieldMapper.update(sf);
                                        return "201-" + moneys.get(0).toString();
                                    }
                                }
                            }else {
                                return code;
                            }
                        }
                    sf.setId(showField.getId());
                    sf.setThumbsCount(thumbsCount);
                    showFieldMapper.update(sf);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return dataCode.toString();
    }

    @Override
    public Integer delete(Integer id) {
        Integer dataCode = thumbsMapper.delete(id);
        if(dataCode > 0){
            Thumbs thumbs = getTById(id);
            ShowField sf = new ShowField();
            ShowField showField = showFieldMapper.getById(Integer.valueOf(thumbs.getIsThumbsId()));
            Integer thumbsCount = 0;
            if (showField.getThumbsCount() != null) {
                thumbsCount = Integer.valueOf(showField.getThumbsCount());
                thumbsCount--;
            }
            sf.setId(showField.getId());
            sf.setThumbsCount(thumbsCount);
            showFieldMapper.update(sf);
        }
        return dataCode;
    }

    private Thumbs getTById(Integer id){
        Thumbs thumbs = thumbsMapper.getById(id);
        return thumbs;
    }

    @Override
    public List<Map<String,Object>> getByIdAndThumbsType(String isThumbsId, Integer thumbsType) {
        List<Thumbs> list = thumbsMapper.getByIdAndThumbsType(isThumbsId,thumbsType);
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("thumbs",list);
        map.put("user",null);
        mapList.add(map);
        if (list != null && list.size() != 0){
            mapList = getUserById(list,map);
        }

        return mapList;
    }

    @Override
    public Map<String,Object> getById(Integer id) {
        Thumbs thumbs = thumbsMapper.getById(id);
        List<Thumbs> list = new ArrayList<Thumbs>();
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("thumbs",list);
        map.put("user",null);
        mapList.add(map);
        if (thumbs != null){
            list.add(thumbs);
            mapList = getUserById(list,map);
        }
        return mapList.get(0);
    }

    @Override
    public Thumbs getIsThumbs(String isThumbsId, Integer thumbsType, String userId) {
        Thumbs thumbs = thumbsMapper.getIsThumbs(isThumbsId,thumbsType,userId);
        return thumbs;
    }

    /**
     * 根据ID与分类查询全部的点赞数据和用户信息
     *
     * @param isThumbsId 被点赞数据ID
     * @param thumbsType 点赞类型（1：生活圈   2：社交圈  3：秀场）
     * @return 点赞列表
     */
    @Override
    public List<ThumbsResult> listThumbsAndUser(String isThumbsId, Integer thumbsType) {
        return thumbsMapper.listUserThumbs(isThumbsId, thumbsType);
    }

    @Override
    public Integer getCountBeLiked(Integer id) {
        Integer thumbsCount = thumbsMapper.getCountBeLiked(id);
        return thumbsCount;
    }


    private List<Map<String,Object>> getUserById(List<Thumbs> list,Map<String,Object> map){
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            for (int index = 0;index < list.size();index++){
                map = new HashMap<String, Object>();
                map.put("thumbs",list.get(index));
                int userId = Integer.parseInt(list.get(index).getUserId());
                User user = userMapper.getById(userId);
                map.put("user",null);
                if (user != null) {
                    map.put("user",user);
                }
                mapList.add(map);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return mapList;
    }
}
